package server;

import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author XA9
 * 
 */
public class BankDatabase {

	private DbConnector db;

	/**
	 * implements the DbConnecter in BankDatabase
	 */

	public BankDatabase() {

		this.db = DbConnector.getInstance();
	}

	/**
	 * Gets user input loginID and password to insert into mysql statement and
	 * subtract the user from the database which loginID and password matches
	 * the user input
	 * 
	 * @param loginId
	 * @param password
	 * @return student
	 * 
	 */

	public Students getStudents(String loginId, String password) {
		String query = "SELECT * FROM Students WHERE LoginId = '" + loginId
				+ "' AND Password = '" + password + "'";
		Students s = null;
		ResultSet rs;
		try {
			rs = db.doQuery(query);
			while (rs.next()) {
				s = new Students(rs.getString(1), rs.getString(2),
						rs.getInt(3), rs.getString(4), rs.getString(5),
						rs.getDouble(6));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * Adds the user-input-money(dkk) to the balance(btc)
	 * 
	 * @param LoginId
	 * @param money
	 */

	public void DepositDKK(String LoginId, double money) {

		String query = "UPDATE Students SET Balance = (Balance + '" + money
				+ "') WHERE (LoginId = '" + LoginId + "')";

		try {
			db.doUpdate(query);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Adds a btc-amount to the balance
	 * 
	 * @param LoginId
	 * @param money
	 */

	public void DepositBtc(String LoginId, double money) {

		String query = "UPDATE Students SET Balance = (Balance + '" + money
				+ "') WHERE (LoginId = '" + LoginId + "')";

		try {
			db.doUpdate(query);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Subtracts the send btc-amount from the balance
	 * 
	 * @param LoginId
	 * @param amount
	 */

	public void SendBtc(String LoginId, double amount) {

		String query = "UPDATE Students SET Balance = (Balance - '" + amount
				+ "') WHERE (LoginId = '" + LoginId + "')";

		try {
			db.doUpdate(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	/**
	 * Get the balance according to a certain loginID
	 * 
	 * @param loginId
	 * @return balance
	 */

	public double getBalance(String loginId) {
		String query = "SELECT * FROM Students WHERE LoginId = '" + loginId
				+ "'";
		Students s = null;
		ResultSet rs;
		try {
			rs = db.doQuery(query);
			while (rs.next()) {
				s = new Students(rs.getString(1), rs.getString(2),
						rs.getInt(3), rs.getString(4), rs.getString(5),
						rs.getDouble(6));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return s.getBalance();
	}

	/**
	 * Boolean statement to check if the customer LoginId and password match
	 * 
	 * @param userLoginId
	 * @param userPassword
	 * @return true or false
	 */

	public boolean authenticateUser(String loginId, String password) {
		Students userStudent = getStudents(loginId, password);

		if (userStudent != null)
			return true;
		else
			return false;
	}

	/**
	 * Picks the current btcRate from the coinmill-website
	 * 
	 * @param btcRate
	 * @return btcRate
	 */

	public double btcRate() {
		double btcRate = -1;

		try {
			URL url = null;
			Document document;

			url = new URL("http://coinmill.com/rss/BTC_DKK.xml");
			URLConnection conn = url.openConnection();
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			document = builder.parse(conn.getInputStream());

			NodeList nl = document.getElementsByTagName("description");

			for (int i = 0; i < nl.getLength(); i++) {
				Node n = nl.item(i);
				NodeList nChilds = n.getChildNodes();

				for (int j = 0; j < nChilds.getLength(); j++) {
					Node nc = nChilds.item(i);
					if (nc.getNodeType() == Node.CDATA_SECTION_NODE) {
						String queryText = nc.getNodeValue().trim();
						String[] lines = queryText.split("\n");
						String line1 = lines[0];
						int indexOfEqual = line1.indexOf('=');
						String dkStr = line1.substring(indexOfEqual + 1,
								line1.indexOf(' ', indexOfEqual + 2));

						btcRate = 1000 * Double.parseDouble(dkStr.trim());

						break;
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return btcRate;
	}
}